<?php

namespace App\Http\Controllers\cz;

use App\Http\Controllers\Controller;
use App\Http\Enums\CzApiEnum;
use App\Jobs\SubmitCzOrder;
use App\Models\BalanceLog;
use App\Models\CustomerProduct;
use App\Models\CzOrder;
use App\Models\CzProduct;
use App\Models\CzSpec;
use App\Models\SysUser;
use App\Models\UserGroupProduct;
use Illuminate\Database\QueryException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CzController extends Controller
{
    public $params;
    public $user;

    public function __construct(Request $request)
    {
        $this->params = $request->all();

        if (!isset($this->params['uid'])) {
            throw new HttpResponseException(error('缺少参数：uid', CzApiEnum::PARAMS_EMPTY_CODE));
        }
        if (!isset($this->params['timestamp'])) {
            throw new HttpResponseException(error('缺少参数：timestamp', CzApiEnum::PARAMS_EMPTY_CODE));
        }
        if (!isset($this->params['sign'])) {
            throw new HttpResponseException(error('缺少参数：sign', CzApiEnum::PARAMS_EMPTY_CODE));
        }

        $user_id = intval($this->params['uid']);
        $timestamp = intval($this->params['timestamp']);
        $user = SysUser::find($user_id);

        $this->user = $user;

        $now_timestamp = time();
        if ($now_timestamp - $timestamp > 60) {
            throw new HttpResponseException(error(CzApiEnum::TIMESTAMP_OUT, CzApiEnum::TIMESTAMP_OUT_CODE));
        }
        if (!$user) {
            throw new HttpResponseException(error(CzApiEnum::USER_NOT_EXIST, CzApiEnum::USER_NOT_EXIST_CODE));
        }
        if ($user->status == 0) {
            throw new HttpResponseException(error(CzApiEnum::USER_STATUS_EXCEPTION, CzApiEnum::USER_STATUS_EXCEPTION_CODE));
        }
        if ($user->can_api == 0) {
            throw new HttpResponseException(error(CzApiEnum::USER_NO_API_PERMIT, CzApiEnum::USER_NO_API_PERMIT_CODE));
        }

        $api_key = get_api_secret($user->api_secret);
        $api_sign = api_sign($this->params, $api_key);
        if ($api_sign != $this->params['sign']) {
            throw new HttpResponseException(error(CzApiEnum::API_SIGN_ERROR, CzApiEnum::API_SIGN_ERROR_CODE));
        }
    }

    public function orderSubmit()
    {
        $mobile = $this->params['mobile'] ?? '';
        //        $product_id = $this->params['product_id'] ?? 0;
        $spec_id = $this->params['spec_id'] ?? 0;

        if (!is_numeric($mobile)) {
            return error(CzApiEnum::MOBILE_FORMAT_ERROR, CzApiEnum::MOBILE_FORMAT_ERROR_CODE);
        }
        $mobile_pref = substr($mobile, 0, 7);
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            return error(CzApiEnum::GET_MOBILE_AREA_INFO_FAIL, CzApiEnum::GET_MOBILE_AREA_INFO_FAIL_CODE);
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error(CzApiEnum::AREA_INFO_NOT_EXIST, CzApiEnum::AREA_INFO_NOT_EXIST_CODE);
        }

        //20220527 获取黑名单号码
        $isBlank = DB::table('cz_mobile_blank')->where('mobile', $mobile)->exists();
        if ($isBlank) {
            return error(CzApiEnum::MOBILE_IS_BLANK, CzApiEnum::MOBILE_IS_BLANK_CODE);
        }

        if (!$area_info) {
            return error(CzApiEnum::AREA_INFO_NOT_EXIST, CzApiEnum::AREA_INFO_NOT_EXIST_CODE);
        }
        $province_id = $area_info->parent_id;

        $spec_info = CzSpec::where('id', $spec_id)->where('id', $spec_id)->first();
        if (!$spec_info) {
            return error(CzApiEnum::SPEC_NOT_EXIST, CzApiEnum::SPEC_NOT_EXIST_CODE);
        }
        if ($spec_info->status == 0) {
            return error(CzApiEnum::SPEC_UNSALE, CzApiEnum::SPEC_UNSALE_CODE);
        }
        $product_id = $spec_info->product_id;

        $product_info = CzProduct::where('id', $product_id)->first();
        if (!$product_info) {
            return error(CzApiEnum::PRODUCT_NOT_EXIST, CzApiEnum::PRODUCT_NOT_EXIST_CODE);
        }
        if ($product_info->status == 0) {
            return error(CzApiEnum::PRODUCT_UNSALE, CzApiEnum::PRODUCT_UNSALE_CODE);
        }
        if ($product_info['province_id'] > 0 && $province_id != $product_info['province_id']) {
            return error(CzApiEnum::MOBILE_NOT_MATH_PRODUCT, CzApiEnum::MOBILE_NOT_MATH_PRODUCT_CODE);
        }
        if ($product_info['city_id'] > 0 && $city_id != $product_info['city_id']) {
            return error(CzApiEnum::MOBILE_NOT_MATH_PRODUCT, CzApiEnum::MOBILE_NOT_MATH_PRODUCT_CODE);
        }


        //获取客户产品
        $user_id = $this->user->id;
        $user = SysUser::find($user_id);
        // 验证是否有api提交权限
        if (!$user['can_api']) {
            return error(CzApiEnum::USER_NO_API_PERMIT, CzApiEnum::USER_NO_API_PERMIT_CODE);
        }
        if ($user->group_id > 0) {
            //客户分组产品
            $user_group_product = UserGroupProduct::with(['channels'])
                ->where('product_id', $product_id)
                ->where('spec_id', $spec_id)
                ->where('user_group_id', $user->group_id)->first();

            if (!$user_group_product) {
                return error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
            }

            $user_price = $user_group_product->user_group_price;
            $is_loop = $user_group_product->is_loop;
            $submit_order_count = $user_group_product->submit_order_count;
            $channel_group_id = $user_group_product->group_id;
        } else {
            //客户产品
            $user_product = CustomerProduct::with(['channels'])
                ->where('product_id', $product_id)
                ->where('spec_id', $spec_id)
                ->where('user_id', $user->id)->first();

            if (!$user_product) {
                return error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
            }

            $user_price = $user_product->user_price;
            $is_loop = $user_product->is_loop;
            $submit_order_count = $user_product->submit_order_count;
            $channel_group_id = $user_product->group_id;
        }

        $order_data = [
            'order_sn' => 'CZ' . date("YmdHis") . 'U' . $user->id . rand(1000, 9999) . rand(1000, 9999),
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $mobile_info->province . '-' . $mobile_info->city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => 1,
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $product_info->hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            'submit_from' => 'api'
        ];
        $balance_log_data = [
            'order_sn' => $order_data['order_sn'],
            'money' => $user_price,
            'bf_balance' => $user->balance,
            'af_balance' => $user->balance - $user_price,
            'bank' => '',
            'type' => 3,
            'remark' => "{$mobile},充值[{$product_info->title}{$spec_info->face_value}]，消费{$user_price}元",
            'user_id' => $user->id,
        ];
        DB::beginTransaction();
        try {
            $is_dec_balance = DB::table('sys_users')
                ->where('id', $user->id)
                ->where('balance', '>=', ($user_price - $user->credit))
                ->decrement('balance', $user_price);
            if (!$is_dec_balance) {
                DB::rollBack();
                return error(CzApiEnum::BALANCE_NOT_ENOUGH, CzApiEnum::BALANCE_NOT_ENOUGH_CODE);
            }
            BalanceLog::create($balance_log_data);
            $model = CzOrder::create($order_data);
            DB::table('cz_order')->where('id', $model->id)->update([
                'create_by' => $user->id,
                'update_by' => $user->id,
            ]);
            DB::commit();
        } catch (QueryException $e) {
            DB::rollBack();
            return error(CzApiEnum::ORDER_SUBMIT_FAIL, CzApiEnum::ORDER_SUBMIT_FAIL_CODE);
        }

        $order_id = $model->id;
        //推送到队列
        //        SubmitCzOrder::dispatch($model);
        //        SubmitCzOrder::dispatchIf($accountActive, $model);
        return success(['data' => [
            //            'order_id' => $order_id,
            'order_sn' => $order_data['order_sn'],
            'price' => $order_data['price'],
        ]], '下单成功');
    }
    public function queryOrder()
    {
        if (!isset($this->params['order_sn'])) {
            return error('缺少参数：order_sn', CzApiEnum::PARAMS_EMPTY_CODE);
        }
        $order_sn = trim($this->params['order_sn']);

        //查询订单
        $order = CzOrder::where('order_sn', $order_sn)->first();
        if (!$order) {
            return error(CzApiEnum::ORDER_NOT_EXIST, CzApiEnum::ORDER_NOT_EXIST_CODE);
        }
        return success([
            'data' => [
                'order_status' => $order->order_status,
            ]
        ]);
    }
    public function queryBalance(Request $request)
    {
        return success([
            'data' => [
                'balance' => $this->user->balance,
                //                'credit' => $this->user->credit,
            ]
        ]);
    }
    public function productList(Request $request)
    {
        //获取用户全部产品
        $user_spec_id = [0];
        if ($this->user->group_id > 0) {
            $params['user_group_id'] = $this->user->group_id;
            $user_spec_id = UserGroupProduct::filter($params)->pluck('spec_id');
            $user_all_price = UserGroupProduct::filter($params)->select('spec_id', 'user_group_price as user_price')->get();
        } else {
            $params['user_id'] = $this->user->id;
            $user_spec_id = CustomerProduct::filter($params)->pluck('spec_id');
            $user_all_price = CustomerProduct::filter($params)->select('spec_id', 'user_price')->get();
        }
        if ($user_all_price) {
            $user_all_price = $user_all_price->toArray();
            $user_all_price = convert_arr_key($user_all_price, 'spec_id');
        }

        $params['mobi_spec_id'] = $user_spec_id;
        //获取产品
        $product_list = CzProduct::with([
            'specs' => function ($query) use ($user_spec_id) {
                $query->whereIn('id', $user_spec_id)->select('id', 'product_id', 'face_value', 'market_price', 'spec_code', 'status');
            },
            'province' => function ($query) {
                $query->select('id', 'short_name');
            },
            'city' => function ($query) {
                $query->select('id', 'short_name');
            },
        ])->filter($params)->select('id', 'title', 'type', 'hf_type', 'isp', 'province_id', 'city_id')->get();
        if ($product_list) {
            $product_list = $product_list->toArray();
            foreach ($product_list as $k1 => $product) {
                foreach ($product['specs'] as $k2 => $spec) {
                    $product_list[$k1]['specs'][$k2]['user_price'] = $user_all_price[$spec['id']]['user_price'];
                }
            }
        }
        if (!$product_list) {
            return error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
        }
        return success([
            'data' => $product_list
        ]);
    }
}
